#!/usr/bin/env bash

CURRENT_PATH=`pwd`
DATE=$(date +%Y%m%d)
TIME=$(date +%H%M%S)
PROJECT_PATH=`pwd`/$PROJECT_NAME
JAR_FILE=$PROJECT_NAME-1.0.jar

# 杀掉原应用进程
killApplication()
{
    pid=$(ps x | grep $JAR_FILE | grep -v grep | awk '{print $1}')
    echo $PROJECT_NAME+" PID is :$pid"
    if [ -n "$pid" ]
    then
        kill -9 $pid
    else
        echo $JAR_FILE+" is not alive!"
    fi
}

echo `pwd`

# 创建备份目录
if [ ! -d `pwd`/backup/$PROJECT_NAME/$DATE ];then
   mkdir -p `pwd`/backup/$PROJECT_NAME/$DATE
fi

cd $PROJECT_PATH

# 创建GC日志文件
if [ ! -d $PROJECT_PATH/jvmlogs ];then
   mkdir -p $PROJECT_PATH/jvmlogs
   touch $PROJECT_PATH/jvmlogs/gc.log
fi

# 使用maven打包项目，生成可执行jar包
mvn clean package

# 备份jar包
cp target/$JAR_FILE ../backup/$PROJECT_NAME/$DATE/$PROJECT_NAME-1.0-$TIME.jar

echo "bike-management application is begin to run ..."

cd target
# 禁止JENKINS执行成功后杀掉应用进程
BUILD_ID=dontKillMe
# 实际调用，杀掉进程
killApplication
# 启动jar包
nohup java -Xmx256m -Xms256m -Xmn128m -XX:PermSize=128m -XX:MaxPermSize=128m -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -XX:+UseParNewGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -XX:CMSFullGCsBeforeCompaction=0 -XX:+CMSClassUnloadingEnabled -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=80 -XX:SoftRefLRUPolicyMSPerMB=0 -XX:+PrintClassHistogram -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintHeapAtGC -Xloggc:../jvmlogs/gc.log -Xdebug -Xrunjdwp:transport=dt_socket,address=18092,server=y,suspend=n -jar -Duser.timezone=Asia/Shanghai -Dspring.profiles.active=demo -Denv=fat -Djava.security.egd=file:/dev/./urandom $JAR_FILE &